package se.webbzon.oschi01.nbt;

import java.io.DataInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import se.webbzon.oschi01.singleton.Singletons;

public abstract class AbstractNBTReader {
	
	public static Map<Byte,TagFactory<?>> factories = new HashMap<Byte,TagFactory<?>>();
	
	static {
		TagFactory<?>[] factories = {
				Singletons.instance(EndTagFactory.class),
				Singletons.instance(ByteTagFactory.class),
				Singletons.instance(ShortTagFactory.class),
				Singletons.instance(IntTagFactory.class),
				Singletons.instance(LongTagFactory.class),
				Singletons.instance(FloatTagFactory.class),
				Singletons.instance(DoubleTagFactory.class),
				Singletons.instance(ByteArrayTagFactory.class),
				Singletons.instance(StringTagFactory.class),
				Singletons.instance(ListTagFactory.class),
				Singletons.instance(CompoundTagFactory.class),
				Singletons.instance(IntArrayTagFactory.class)
			};
			
		for (TagFactory<?> factory : factories)
			AbstractNBTReader.factories.put(factory.getId(), factory);
	}
	
	private Map<Byte,TagFactory<?>> f;
	
	protected AbstractNBTReader() {
		this.f = factories;
	}
	
	protected Tag<?> read(DataInputStream dis) throws IOException {
		byte tagId = dis.readByte();
		TagFactory<?> factory = f.get(tagId);
		if (factory == null) 
			throw new IOException("Unknown tag id: " + tagId);
		
		String tagName;
		if (!factory.isNameless()) {
			short size = dis.readShort();
			if (size == 0) 
				tagName = "";
			else {
				byte[] data = new byte[size];
				dis.readFully(data);
				tagName = new String(data,"utf-8");
			}
		} else
			tagName = "";
		
		return factory.readTag(tagName, dis);
	}

}
